<template>
  <view class="body">
    <view class="main">
      <view class="window">
        <image  :style="'width:'+canvasWidth+'px;height:'+canvasHeight+'px;background:'+canvasBackgroundColor"  :src="canvasImages"></image>
        <image v-show="buildOver" class="water" src="https://bj.bcebos.com/txy-dev/txy/zjz/watermark.png"></image>
        <!-- <canvas type="2d" id="myCanvas" style="width: {{canvasWidth}}px;height: {{canvasHeight}}px;"></canvas> -->
      </view>
      <view class="choose-color">
        <view class="title">选择背景色</view>
        <view class="color-btn">
          <block v-for="(item,index) in color_arr" :key="item.id">
            <view @click="chooseColor(index)"  class="circle" :class="item.active?'active':''"
              :style="'background:'+ item.color"></view>
          </block>
        </view>
      </view>
    </view>
    <view class="showImg2" :style="'width:' + initWidth + 'px;height:' + initHeight +'px'">
      <canvas style="width:100%;height:100%" canvas-id="myselfCanvas"></canvas>
    </view>
    <view class="showImg2" :style="'width:' + initWidth + 'px;height:' + initHeight +'px'">
      <canvas style="width:100%;height:100%" canvas-id="downloadCanvas"></canvas>
    </view>
    <view class="footer">
      <view @click="pictureClick">上传图片</view>
      <view @click="downloadimg">保存图片</view>
    </view>
  </view>
</template>
<script>
import {bodyAnalysis} from '../../util/url.js'
import {getImageInfos,getAccessToken} from '../../util/api.js'
import base64src from './base64src.js'
import {savePoster} from './saveImg.js'
import listSize from '../../util/data.js'

import {fileBase64Size} from '../../util/imgSize.js'
let IMG_RATIO
let ratio = 295/413
let initWidth = 295
let initHeight = 413
let scrollTop = 250
export default {
  onLoad(option) {
    let id = option.id
    listSize.forEach(selectData => {
      if (selectData.id == id) {
        ratio = selectData.width / selectData.height
        initWidth = selectData.width;
        initHeight = selectData.height;
        this.selectData = selectData
        uni.setNavigationBarTitle({
          title: selectData.name
        })
      }
    })
    this.getImgInfo(option.filePath)
  },
  data() {
    return {
      color_arr: [{
        id: '0',
          active: true,
          name: 'white',
          color: '#FFFFFF'
        },
        {
          id: '1',
          active: false,
          name: 'blue',
          color: '#428EDA'
        },
        {
          id: '2',
          active: false,
          name: 'red',
          color: '#FE0000'
        },
        {
          id: '3',
          active: false,
          name: 'gray',
          color: '#B1B1B1'
        }
      ],
      // 画布背景颜色
      canvasBackgroundColor: '#FFFFFF',
      // 画板的换算比例宽度
      canvasWidth: 200,
      // 画板的固定高度
      canvasHeight: 280,
      // 人像分离后用于生成canvas的图片
      canvasImages: '',
      foreground: '',
      location: {},
      initWidth: initWidth,
      initHeight: initHeight,
      selectData: {},
      buildOver: false
    }
  },
  methods: {
    errAlert() {
      uni.hideLoading()
    },
    chooseColor(index) {
      // 清理选中状态
      this.color_arr.forEach((item, cindex) => {
        if (cindex === index) {
          item.active = true
          this.canvasBackgroundColor = item.color
        }else {
          item.active = false
        }
      })
    },
    pictureClick() {
      const _this = this;
        let typelist = ['album']
        uni.chooseImage({
          count: 1,
          sourceType: typelist,
          success: (res)=> {
            // _this.toBase64(res.tempFilePaths[0])
            fileBase64Size(res.tempFilePaths[0]).then(length => {

              if (length > 4 * 1024 * 1024) {
                uni.showToast({
                  title: '上传图片最大为4M,请重新选择图片',
                  icon:'none',
                  duration: 2000
                });
              }else{
                _this.getImgInfo(res.tempFilePaths[0])
              }
            })
            // _this.getImgInfo(res.tempFilePaths[0])
          }
        });
    },
    toBase64(file) {
      let _this = this
      uni.getFileSystemManager().readFile({
          filePath: file, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => {
              // 成功的回调
              // 'data:image/jpeg;base64,'
              let base64 = res.data;
              _this.getImgInfos(base64)
          }
      });
    },
    getImgInfos(base64) {
      const _this = this
      getAccessToken().then(token => {
        let data = {
          access_token: token,
          image: base64
        }
        getImageInfos(data).then(res => {
          let bodyAns = res.bodyAns
          let bodySeg = res.bodySeg
          _this.initImgData(bodyAns,bodySeg)
        },() => {
          uni.showToast({
            title: '请求接口出错了',
            icon:'none',
            duration: 2000
          });
        })
      })
    },
    getImgInfo(filePath) {
      const _this = this;
      _this.canvasImages = filePath
      this.buildOver = false
      uni.showLoading({
        title: "图片制作中...",
      });
      _this.toBase64(filePath)
      // wx.uploadFile({
      //   url: bodyAnalysis,
      //   filePath: filePath,//获取的图片临时路径
      //   name: 'file',//图片标识,后台可用标识获取该图片,也可以用下标获取
      //   success(res) {
      //     if (res.statusCode === 200) {

      //       let bodyData = JSON.parse(res.data)
      //       let bodyAns = bodyData.data.bodyAns
      //       let bodySeg = bodyData.data.bodySeg
      //       _this.initImgData(bodyAns,bodySeg)
      //     }else{
      //       uni.showToast({
      //         title: '请求接口出错了',
      //         icon:'none',
      //         duration: 2000
      //       });
      //     }
      //   },
      //   fail(res){
      //     console.log(res);
      //   }
      // });
    },
    imgwidthsum(data) {
      let body_parts = data.body_parts
      return {
        top_head: body_parts.top_head, 
        left_shoulder: body_parts.left_shoulder,
        right_shoulder: body_parts.right_shoulder
      }
    },
    initImgData(bodyAns,bodySeg) {
      if (bodyAns.person_num > 1) {
        uni.showToast({
          title: '图片检测到多个人像，请重新上传',
          icon:'none',
          duration: 2000
        });
        return
      }
      if (bodyAns.person_num == 0) {
        uni.showToast({
          title: '图片未检测到人像，请重新上传',
          icon:'none',
          duration: 2000
        });
        return
      }
      let widthInfo = bodyAns.person_info[0]
      let location = this.imgwidthsum(widthInfo)
      this.location = location
      let foreground = bodySeg.foreground
      this.foreground = foreground
      this.previewImg('data:image/png;base64,' + foreground, location).then(filePath => {
        this.canvasImages = filePath
        this.buildOver = true
      })
    },
    downloadimg() {
      let foreground = this.foreground
      let location = this.location
      this.previewImg('data:image/jpg;base64,' + foreground, location, this.canvasBackgroundColor).then(filePath => {
        savePoster(filePath, this.selectData.dpi)
      })
    },
    previewImg(imageSrc, location, color) {
      let _this = this
      return new Promise((resolve) => {
        let pathName = new Date().getTime()
        base64src(imageSrc,pathName).then(filePath => {
          uni.getImageInfo({
            src: filePath,
            success: function success(res) {
              console.log(res)
              let imgH = res.height;
              let imgW = res.width;
              /* 图片的宽高比  */
              IMG_RATIO = imgW / imgH;
              let IMG_REAL_W,IMG_REAL_H
              
              IMG_REAL_H = initHeight
              IMG_REAL_W = IMG_REAL_H*IMG_RATIO
              let canH = imgW * IMG_REAL_H / IMG_REAL_W
              const ctx = uni.createCanvasContext("myselfCanvas", _this);
              _this.imageW = IMG_REAL_W
              _this.imageH = IMG_REAL_H
              if (color) {
                ctx.setFillStyle(color)
                ctx.fillRect(0,0,IMG_REAL_W,IMG_REAL_H)
              }
              ctx.drawImage(res.path, 0, 0, IMG_REAL_W, IMG_REAL_H);
              
              let x = location.right_shoulder.x //203
              let y = location.top_head.y - scrollTop // 386
              let x1 = location.left_shoulder.x //888
              // 获取画布要裁剪的位置和宽度   均为百分比 * 画布中图片的宽度    保证了在微信小程序中裁剪的图片模糊  位置不对的问题 canvasT = (_this.cutT / _this.cropperH) * (_this.imageH / pixelRatio)
              var canvasW = ((x1 - x) / imgW) * IMG_REAL_W;
              var canvasH = canvasW/ratio // canvasW * 413 / 295
              var canvasL = (x / imgW) * IMG_REAL_W;
              var canvasT = (y / imgH) * IMG_REAL_H;
              ctx.draw(false,(ret)=>{						 
                uni.showToast({
                  icon:'success',
                  mask:true,
                  title: '绘制完成',
                });
                
                uni.canvasToTempFilePath({ // 保存canvas为图片
                  x: canvasL,
                  y: canvasT,
                  width: canvasW, //canvasH,
                  height: canvasH, //canvasH,
                  destWidth: initWidth,
                  destHeight: initHeight,
                  canvasId: 'myselfCanvas',
                  quality: 1,
                  fileType: color? 'jpg': 'png',
                  complete: function(res) {
                    // 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
                    resolve(res.tempFilePath)	
                    // _this.canvasImages = res.tempFilePath
                    
                  } ,
                })
              });
            }
          })
        })
      })
    }
  }
}
</script>
<style>
@import './index.css';
</style>